<template>
	<view class="container">
		<view class="footer">
			<input v-model="searchQuery" placeholder="搜索学生(ID,姓名,班级,学号)" class="search-input" />
			<button @click="showAddModal" class="add-button">添加学生</button>
			<button @click="sortStudent" class="sort-button">
				{{ sortMthod === 'asc'? '按成绩降序排序':'按成绩升序排序'}}
			</button>
		</view>
		<table class="student-table">
			<thead>
				<tr>
					<th>ID</th>
					<th>姓名</th>
					<th>班级</th>
					<th>学号</th>
					<th @click="sortStudent" class="sortable-header">
						成绩<span>{{ sortMthod === 'asc'?'↑':'↓'}}</span>
					</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="student in sortedStudents" :key="student.id">
					<td>{{student.id}}</td>
					<td>{{student.student_name}}</td>
					<td>{{student.student_class}}</td>
					<td>{{student.student_number}}</td>
					<td>{{student.student_score}}</td>
					<td>
						<button @click="editStudent(student)" class="edit-button">编辑</button>
						<button @click="deleteStudent(student.id)" class="delete-button">删除</button>
					</td>
				</tr>
			</tbody>
		</table>
		<view class="pagination">
			<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
			<span>第{{currentPage}} 页，共{{totalPages}}页</span>
			<button @click="nextPage" :disabled="currentPage>=totalPages">下一页</button>
		</view>


		<!-- 添加和编辑模态框 -->
		<modal v-if="isModalVisible" class="modal">
			<view class="modal-content">
				<text>输入学生信息：</text>
				<input v-model="currentStudent.student_name" placeholder="姓名" class="modal-input" />
				<input v-model="currentStudent.student_class" placeholder="班级" class="modal-input" />
				<input v-model="currentStudent.student_number" placeholder="学号" class="modal-input" />
				<input v-model="currentStudent.student_score" placeholder="成绩" class="modal-input" />
				<view class="modal-buttons">
					<button @click="saveStudent()" class="confirm-button">确定</button>
					<button @click="isModalVisible = false" class="cancel-button">取消</button>
				</view>
			</view>
		</modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				students: [{
					id: '',
					student_name: '',
					student_class: '',
					student_number: '',
					student_score: '',
				}],
				isModalVisible: false,
				currentStudent: {
					id: null,
					student_name: '',
					student_class: '',
					student_number: '',
					student_score: '',
				},
				searchQuery: '',
				sortMthod: 'asc', // 默认升序
				currentPage: 1, // 当前页面
				pageSize: 5,  //每页多少数据
			};
		},
		computed: {
			filteredStudents() {
				// console.log(this.searchQuery);
				if (!this.searchQuery) {
					return this.students;
				}
				this.currentPage = 1;
				const query = this.searchQuery.toLowerCase();
				return this.students.filter(student =>
					student.id.toString().includes(query) ||
					student.student_name.toLowerCase().includes(query) ||
					student.student_class.toLowerCase().includes(query) ||
					student.student_number.toString().includes(query)
				);
			},
			sortedStudents() {
				// 过滤   排序   分页
				const filtered = this.filteredStudents;
				
				// 排序
				const sorted = filtered.sort((a, b) => {
					const scoreA = a.student_score;
					const scoreB = b.student_score;
					return this.sortMthod === 'asc' ? scoreA - scoreB : scoreB - scoreA;
				});
				
				const start = (this.currentPage -1)*this.pageSize;
				const end = start + this.pageSize;
				return sorted.slice(start,end);  // index[start]~index[end]
				
				// return this.filteredStudents.sort((a, b) => {
				// 	const scoreA = a.student_score;
				// 	const scoreB = b.student_score;
				// 	return this.sortMthod === 'asc' ? scoreA - scoreB : scoreB - scoreA;
				// });
			},
			// reversedSortedStudents() {
			// 	return this.sortedStudents.reverse(); // 反转已排序的数组
			// }
			totalPages(){
				return Math.ceil(this.filteredStudents.length/this.pageSize);
			}

		},
		methods: {
			prevPage(){
				
				if(this.currentPage > 1){
					this.currentPage --;
				}
			},
			nextPage(){
				if(this.currentPage < this.totalPages);
				this.currentPage ++;
			},
			async fetchStudents() {
				const response = await uni.request({
					url: 'http://localhost:8088/api/demo/get_stu',
					method: 'GET',
				});
				this.students = response.data.data || [];
				console.log(response);
			},
			showAddModal() {
				this.currentStudent = {
					id: null,
					student_name: '',
					student_class: '',
					student_number: '',
					student_score: '',
				}
				this.isModalVisible = true;
			},
			async saveStudent() {
				const url = this.currentStudent.id ?
					`http://localhost:8088/api/demo/edit_stu/${this.currentStudent.id}` :
					'http://localhost:8088/api/demo/stu_add';
				await uni.request({
					url,
					method: 'POST',
					data: this.currentStudent,
					success: (res) => {
						if (this.currentStudent.id) {
							//修改
							if (res.data.msg === '编辑成功') {
								uni.showToast({
									'title': '编辑成功',
									icon: 'success'
								});
								this.fetchStudents();
							} else {
								uni.showToast({
									title: '编辑失败',
									icon: 'error'
								});
							}
						} else {
							//添加
							if (res.data.msg === '添加成功') {
								uni.showToast({
									'title': '添加成功',
									icon: 'success'
								});
								this.fetchStudents();
							} else {
								uni.showToast({
									title: '添加失败',
									icon: 'error'
								});
							}
						}
						this.isModalVisible = false; // uni.showToast({'添加成功', icon: 'success' });
					}
				});
			},
			async deleteStudent(id) {
				await uni.request({
					url: 'http://localhost:8088/api/demo/del_stu',
					method: 'POST',
					data: {
						id
					},
					success: (res) => {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						this.fetchStudents();
					},
					fail: () => {
						// 网络请求失败的处理
						uni.showToast({
							title: '请求失败，请重试',
							icon: 'error'
						});
					}
				})
			},
			editStudent(student) {
				this.currentStudent = {
					...student
				}
				this.isModalVisible = true;
			},
			sortStudent() {
				this.sortMthod = this.sortMthod === 'asc' ? 'desc' : 'asc';
			}
		},

		mounted() {
			this.fetchStudents();

		}
	};
</script>

<style>
	.container {
		padding: 20px;
		font-family: Arial, sans-serif;
	}

	.footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.search-input {
		padding: 10px;
		width: 70%;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.add-button,
	.sort-button {
		padding: 10px 15px;
		background-color: #4CAF50;
		/* 绿色 */
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	.add-button:hover,
	.sort-button:hover {
		background-color: #45a049;
		/* 深绿色 */
	}

	.student-table {
		width: 100%;
		border-collapse: collapse;
	}

	th,
	td {
		border: 1px solid #ccc;
		padding: 12px;
		text-align: left;
	}

	th {
		background-color: #f2f2f2;
	}

	.edit-button,
	.delete-button {
		padding: 5px 10px;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.edit-button {
		background-color: #A0C4FF;
		color: white;
	}

	.edit-button:hover {
		background-color: #0b7dda;
	}

	.delete-button {
		background-color: #FFABAB;
		color: white;
	}

	.delete-button:hover {
		background-color: #da190b;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-content {
		background: white;
		padding: 20px;
		border-radius: 8px;
		width: 300px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
	}

	.modal-input {
		margin: 10px 0;
		padding: 8px;
		border: 1px solid #ccc;
		border-radius: 4px;
		width: calc(100% - 16px);
	}

	.modal-buttons {
		display: flex;
		justify-content: space-between;
	}

	.confirm-button,
	.cancel-button {
		padding: 10px;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.confirm-button {
		background-color: #4CAF50;
		color: white;
	}

	.confirm-button:hover {
		background-color: #45a049;
	}

	.cancel-button {
		background-color: #f44336;
		color: white;
	}

	.cancel-button:hover {
		background-color: #da190b;
	}
	
	.pagination {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 10px;
		}
	
		.pagination button {
			background-color: #007BFF;
			color: white;
			border: none;
			padding: 8px 12px;
			margin: 0 5px;
			border-radius: 4px;
			cursor: pointer;
			transition: background-color 0.3s;
		}
	
		.pagination button:hover:not(:disabled) {
			background-color: #0056b3;
		}
	
		.pagination button:disabled {
			background-color: #ccc;
			cursor: not-allowed;
			opacity: 0.7;
		}
	
		.pagination span {
			margin: 0 10px;
			font-weight: bold;
		}
</style>